
//
//  NSDate+Extension.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/2.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
extension NSDate {
    /* 根据一个字符串快速创建一个NSDate */
    class func createDate(timeStr: String, formatterStr: String) -> NSDate {
        let formatter = NSDateFormatter()
        formatter.dateFormat = formatterStr
        formatter.locale = NSLocale(localeIdentifier: "en")
        return formatter.dateFromString(timeStr)!
    }
    
    /* 将一个NSDate转换为对应的描述 */
    func descriptionStr() -> String {
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en")

        let calendar = NSCalendar.currentCalendar()
        var formatterStr = "HH:mm"
        /* 创建日期是今天 */
        if calendar.isDateInToday(self) {
            let interval = Int(NSDate().timeIntervalSinceDate(self))
            if interval < 60 {
                /* 刚刚 */
                return "刚刚"
            } else if interval < 60 * 60 {
                /* X分钟前 */
                return "\(interval / 60)分钟前"
            } else if interval < 60 * 60 * 24 {
                /* X小时前（当天） */
                return "\(interval / (60 * 60))小时前"
            }
        } else if calendar.isDateInYesterday(self) {
            /* 昨天 */
            formatterStr = "昨天" + formatterStr
        } else {
            /* 更早之前 */
            let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
            if comps.year >= 1 {
                /* 一年前 */
                formatterStr = "yyyy-MM-dd " + formatterStr
            } else {
                /* 一年内 */
                formatterStr = "MM-dd " + formatterStr
            }
        }
        formatter.dateFormat = formatterStr
        return formatter.stringFromDate(self)
    }
}
